package com.example.hp.storeapp;

import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;

import com.example.hp.storeapp.base.BaseActivity;
import com.example.hp.storeapp.fragment.LoginFragment;
import com.example.hp.storeapp.fragment.MainFragment;

public class MainActivity extends BaseActivity {

    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;

    private LoginFragment loginFragment;

    private MainFragment mainFragment;

    private SharedPreferences preferences;
    private final  String fileName = "food";
    private  final  int mode = MODE_PRIVATE;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        preferences = getSharedPreferences(fileName,mode);

        fragmentManager =getSupportFragmentManager();

        //先判断用户是否已经登录,如果登录进入主界
        // 否则，显示登录界面getLoginState()isLogined()
        boolean loginState = getLoginState();
        if (loginState) {
            //直接进入主界面
            showMainFragment();
            userId = getSavedUserId();//获取已经存储的用户Id

        }else{
            //显示登录
            showLoginFragment();

        }
    }





    public void  showLoginFragment(){
        transaction = fragmentManager.beginTransaction();

        loginFragment = new LoginFragment();
        transaction.add(R.id.fragment_holder,loginFragment);

        transaction.commit();

    }
    private void showMainFragment(){
        transaction = fragmentManager.beginTransaction();

        mainFragment = new MainFragment();
        transaction.add(R.id.fragment_holder,mainFragment);
        transaction.commit();

    }
    public  void  replaceLoginFragment(){

        mainFragment = new MainFragment();
        transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_holder,mainFragment);

        transaction.commit();
    }

    private  boolean getLoginState(){

        String userId =getSavedUserId();


        return !userId.equals("-1");
    }
    private  String getSavedUserId(){

        String userId = preferences.getString("user_id","-1");
        return userId;
    }

    public   void setSavedUserId(String userId){

        SharedPreferences.Editor editor = preferences.edit();

        editor.putString("user_id",userId);

        editor.commit();


    }

}

